namespace MicroFrameworkDriverLibrary.Devices
{
    using System;
    using System.Reflection;
    using Microsoft.SPOT.Hardware;
    using System.Runtime.CompilerServices;

    public static class I2CDeviceExtensions
    {
        public static I2CDevice.I2CWriteTransaction xCreateWriteTransaction(this I2CDevice i2cDevice, byte[] buffer, uint internalAddress, byte internalAddressSize)
        {
            I2CDevice.I2CWriteTransaction writeTransaction = I2CDevice.CreateWriteTransaction(buffer);
            Type writeTransactionType = typeof(I2CDevice.I2CWriteTransaction);

            FieldInfo fieldInfo = writeTransactionType.GetField("Custom_InternalAddress", BindingFlags.NonPublic | BindingFlags.Instance);
            if (fieldInfo != null)
            {
                fieldInfo.SetValue(writeTransaction, internalAddress);

                fieldInfo = writeTransactionType.GetField("Custom_InternalAddressSize", BindingFlags.NonPublic | BindingFlags.Instance);
                fieldInfo.SetValue(writeTransaction, internalAddressSize);
            }
            return writeTransaction;
        }


        public static I2CDevice.I2CReadTransaction xCreateReadTransaction(this I2CDevice i2cDevice, byte[] buffer, uint internalAddress, byte internalAddressSize)
        {
            I2CDevice.I2CReadTransaction readTransaction = I2CDevice.CreateReadTransaction(buffer);
            Type readTransactionType = typeof(I2CDevice.I2CReadTransaction);

            FieldInfo fieldInfo = readTransactionType.GetField("Custom_InternalAddress", BindingFlags.NonPublic | BindingFlags.Instance);
            if (fieldInfo != null)
            {
                fieldInfo.SetValue(readTransaction, internalAddress);

                fieldInfo = readTransactionType.GetField("Custom_InternalAddressSize", BindingFlags.NonPublic | BindingFlags.Instance);
                fieldInfo.SetValue(readTransaction, internalAddressSize);
            }
            return readTransaction;
        }
    }
}
